Python 24일 코스 - Day 13: 클래스 기초

Day 13: 클래스 기초

클래스 정의

class Dog:
    species = "Canis familiaris"  # 클래스 변수

    def __init__(self, name, age):
        self.name = name   # 인스턴스 변수
        self.age = age

    def bark(self):
        return f"{self.name}이(가) 멍멍!"

    def info(self):
        return f"{self.name}, {self.age}살"

my_dog = Dog("바둑이", 3)
print(my_dog.bark())   # 바둑이이(가) 멍멍!
print(my_dog.info())   # 바둑이, 3살

클래스 변수 vs 인스턴스 변수

구분클래스 변수인스턴스 변수
위치클래스 본문__init__ 내부
공유모든 인스턴스 공유각 인스턴스 고유
접근Class.var 또는 self.varself.var

은행 계좌 예제

class BankAccount:
    def __init__(self, owner, balance=0):
        self.owner = owner
        self._balance = balance  # 관례적 비공개

    def deposit(self, amount):
        if amount <= 0:
            raise ValueError("입금액은 양수여야 합니다")
        self._balance += amount
        return self._balance

    def withdraw(self, amount):
        if amount > self._balance:
            raise ValueError("잔액이 부족합니다")
        self._balance -= amount
        return self._balance

    def get_balance(self):
        return self._balance

account = BankAccount("철수", 10000)
account.deposit(5000)
account.withdraw(3000)
print(f"잔액: {account.get_balance()}원")  # 잔액: 12000원

프로퍼티

class Circle:
    def __init__(self, radius):
        self._radius = radius

    @property
    def radius(self):
        return self._radius

    @radius.setter
    def radius(self, value):
        if value < 0:
            raise ValueError("반지름은 음수일 수 없습니다")
        self._radius = value

    @property
    def area(self):
        return 3.14159 * self._radius ** 2

c = Circle(5)
print(c.area)     # 78.53975
c.radius = 10
print(c.area)     # 314.159

오늘의 연습문제

  1. Student 클래스를 만들어 이름, 과목별 점수, 평균 계산 기능을 구현하세요.
  2. Rectangle 클래스에 넓이, 둘레, 정사각형 여부를 프로퍼티로 구현하세요.
  3. TodoList 클래스로 할 일 추가, 삭제, 완료 표시 기능을 만드세요.

이 글이 도움이 되었나요?